#include "types/recinfo_cache.h"
#include "modules/buffer_mgr.h"
#include "types/bptree.h"

recinfo_cache * recinfo_cache::rc = NULL;

void flush_cache(string &tablename, UINT32 block_num)
{
	recinfo_cache::inst() -> flush_cache(tablename, block_num);
}

recinfo_cache::recinfo_cache()
{
	BufferManager &bm = BufferManager::inst();
	bm.reg_commit_callback(::flush_cache);
}

bool recinfo_cache::is_cached(RecordId id)
{
	for(int i=0; i<cache.size(); i++)
	{
		if((cache[i].r.id.block_num == id.block_num) && (cache[i].r.id.slot_num == id.slot_num))
		{
			return true;
		}
	}
	return false;
}
	
void recinfo_cache::insert(string &tblname, Record r)
{
	recinfo_cache::insert(tblname, r, vector<string>());
}

void recinfo_cache::insert(string &tblname, Record r, vector<string> index_name)
{
	info i = {tblname, r, index_name};
	//printf("\nInserting record in cache: %s %d %d", tblname.c_str(), r.id.block_num,r.id.slot_num);	
	cache.push_back(i);
}

vector<Record> recinfo_cache::get_uncommitted_records(string tblname)
{
	vector<Record> result;
	for(int i=0; i<cache.size(); i++)
	{
		if(cache[i].tablename == tblname)
		{
			result.push_back(cache[i].r);
		}
	}
	return result;
}

void recinfo_cache::flush_cache(string &tablename, UINT32 block_num)
{
	//printf("\nGot commit signal for %s %d",tablename.c_str(), block_num);
	for(int i=0; i<cache.size(); i++)
	{
		if( (cache[i].tablename == tablename) && (cache[i].r.id.block_num == block_num))
		{
			//Update the indices
			for(int j=0; j < cache[i].indices.size(); j++)
			{
				if(cache[i].indices[j] != "")
				{
					UINT32 *rec_data = (UINT32 *)cache[i].r.get_data();	
					index_data d = {rec_data[j], cache[i].r.id};
					//printf("\nCreating bptree object : %s",cache[i].indices[j].c_str());
					bptree index(cache[i].indices[j]);
					index.RecInsert(d);
					//printf("\nUpdating Index : %s %s %d %d", tablename.c_str(), cache[i].indices[j].c_str(), cache[i].r.id.block_num,cache[i].r.id.slot_num);
				}
			}
			//Erase the entry from cache
			cache.erase( cache.begin() + i);
			i--;
		}
	}
}

